package edu.mama.college.controller;

import edu.mama.college.mapper.SmsSendRecordMapper;
import edu.mama.college.model.JsonResult;
import edu.mama.college.model.SmsSendRecord;
import edu.mama.college.model.User;
import edu.mama.college.service.UserService;
import edu.mama.college.service.UserStudyRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Map;
import java.util.UUID;

@Slf4j
@RestController
public class AccountController {

    @Autowired
    private UserService userService;

    @Autowired
    private SmsSendRecordMapper smsSendRecordMapper;

    @Autowired
    private UserStudyRecordService userStudyRecordService;

    @Value("${upload.location}")
    private String fileLocation;

    @Value("${upload.image}")
    private String imagePath;




    @PostMapping("/user/nickname")
    public JsonResult updateNickname(@RequestParam("nickname") String nickname,
                                     @SessionAttribute(value="user",required = false) User user
    ){

        user.setNickname(nickname);

        // 更新Session
        userService.updateNickname(user);

        return JsonResult.success();

    }

    @PostMapping("/user/password")
    public JsonResult updatePassword(
            @RequestBody Map<String, String> param,
            @SessionAttribute(value="user",required = false) User user,
            HttpServletRequest request
    ){

        String oldPwd =  param.get("oldPwd");
        String newPwd =  param.get("newPwd");
        String newPwdRepeat =  param.get("newPwdRepeat");
        if(newPwdRepeat == null || !newPwdRepeat.equals(newPwd)){
            return JsonResult.fail("两次密码不一致");
        }
        User userInfo = userService.findByMobile(user.getMobile());
        if(!userInfo.getPassword().equals( DigestUtils.md5DigestAsHex(oldPwd.getBytes()))){
            return JsonResult.fail("旧密码输入错误");
        }
        userInfo.setPassword(DigestUtils.md5DigestAsHex(newPwd.getBytes()));
        userService.updatePassword(userInfo);

        // 清除session
        request.getSession().invalidate();

        return JsonResult.success();
    }

    @PostMapping("/user/avatar")
    public JsonResult avatar(@RequestParam(value = "file") MultipartFile avatar,
                             @SessionAttribute(value="user",required = false) User user){
        if (avatar.isEmpty()) {
            return JsonResult.fail("文件为空");
        }
        String fileName = UUID.randomUUID().toString();
        // 设置文件上传路径
        String filePath = fileLocation+imagePath+fileName;



        try {
            File file = new File(filePath);
            if(!file.exists()){
                file.mkdirs();
            }
            // springboot封装的方法，将文件上传至路径
            avatar.transferTo(file);
            // 更新Session
            user.setAvatar(imagePath+fileName);
            userService.updateAvatar(user);
            return JsonResult.success("上传成功");
        } catch (Exception e) {
            log.error("上传头像失败：",e);
            return JsonResult.fail("上传失败");
        }
    }

    /**
     * 我的学习数据统计
     */
    @GetMapping("/user/statistic")
    public JsonResult statistic(@SessionAttribute("user") User user){

        Map<String,Integer> dataMap = userStudyRecordService.statistic(user.getId());
        return JsonResult.success(dataMap);
    }

    /**
     * 发送验证码
     */
    @GetMapping("/user/mobile/captcha")
    public JsonResult captcha(@RequestParam("mobile") String mobile){
        User user = userService.findByMobile(mobile);
        if(user != null){
            return JsonResult.fail("该手机号已被占用");
        }

        String code =  userService.getSmsCode(6);

        userService.sendSms(mobile,code);
        System.out.println("验证码："+code);
        return JsonResult.success();
    }

    /**
     * 更换手机号
     */
    @PostMapping("/user/mobile")
    public JsonResult changeMobile(@RequestBody Map<String,String> param,
                                   @SessionAttribute(value="user",required = false) User user
                                   ){

        String mobile =  param.get("mobile");
        String code =  param.get("captcha");
        SmsSendRecord record = smsSendRecordMapper.getRecord(mobile,code);
        if(record == null){
            return JsonResult.fail("验证码错误");
        }
        userService.changeMobile(mobile,user.getId());
        user.setMobile(mobile);
        return JsonResult.success();

    }


}
